import Footer from '@/components/Footer';
import { MyMessageBox, SelectLang } from '@/components/RightContent';
import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import type { RunTimeLayoutConfig } from '@umijs/max';
import { history } from '@umijs/max';
import { stringify } from 'querystring';
import defaultSettings from '../config/defaultSettings';
import {
  AvatarDropdown,
  AvatarName,
} from './components/RightContent/AvatarDropdown';
import { DeployConfigPublishNotification } from '@/components/MyNotification/LocalNotification';

import * as api from '@/services/account';

const isDev = process.env.NODE_ENV === 'development';
const isTest = REACT_APP_ENV == 'test';

let title = `${defaultSettings.title}`;


if (isTest) {
  title += '-测试环境';
}

let waterMarkContent = '';
if (isDev) {
  waterMarkContent = '开发环境';
} else if (isTest) {
  waterMarkContent = title;
}

console.log('REACT_APP_ENV: ', REACT_APP_ENV, ' title:', title);

const loginPath = '/login';

// /** 获取用户信息比较慢的时候会展示一个 loading */
// export const initialStateConfig = {
//   loading: <MyLoading loading />,
// };

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.AdminPassport;
  fetchUserInfo?: () => Promise<API.AdminPassport | undefined>;
}> {
  const fetchUserInfo = async () => {
    console.log(
      'isDev: ',
      isDev,
      ' isTest: ',
      isTest,
      ' REACT_APP_ENV: ',
      REACT_APP_ENV,
    );

    const result = await api.currentUser();
    //console.log('fetchUserInfo.result: ', result);
    if (result.success) {
      return result.data;
    }
    return undefined;
  };

  defaultSettings.title = title;

  //console.log('history.location.pathname: ', history.location.pathname);

  // 如果是登录页面，不执行
  if (history.location.pathname !== loginPath) {
    const currentUser = await fetchUserInfo();
    //console.log('getInitialState.currentUser:', currentUser);

    return {
      settings: defaultSettings as Partial<LayoutSettings>,
      currentUser: currentUser,
      fetchUserInfo,
    };
  }

  return {
    settings: defaultSettings as Partial<LayoutSettings>,
    fetchUserInfo,
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  // console.log(initialState);
  return {
    pageTitleRender: false,
    menuHeaderRender: undefined,
    menu: {
      defaultOpenAll: true,
      ignoreFlatMenu: true,
      autoClose: false,
    },
    menuProps: {
      mode: 'inline',
      inlineIndent: 24,
    },
    actionsRender: () => [
      // <Question key="doc" />,
      <MyMessageBox key="myMessageBox" />,
      <SelectLang key="SelectLang" />,
      <DeployConfigPublishNotification />
    ],
    avatarProps: {
      src: '/avatar.png',
      title: <AvatarName />,
      render: (_, avatarChildren) => {
        return <AvatarDropdown menu={true}>{avatarChildren}</AvatarDropdown>;
      },
    },
    waterMarkProps: {
      content: waterMarkContent,
    },
    // headerContentRender: () => <ProBreadcrumb />,
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { search, pathname } = history.location;
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        if (pathname == '' || pathname == '/') {
          history.push(loginPath);
        } else {
          history.replace({
            pathname: loginPath,
            search: stringify({
              redirect: pathname + search,
            }),
          });
        }
      }
    },    
    // onPageChange: () => {
    //   const { search, pathname } = history.location;
    //   // 如果没有登录，重定向到 login
    //   if (!initialState?.currentUser && pathname !== loginPath) {
    //     if (pathname == '' || pathname == '/') {
    //       history.push(loginPath);
    //     } else {
    //       history.replace({
    //         pathname: loginPath,
    //         search: stringify({
    //           redirect: pathname + search,
    //         }),
    //       });
    //     }
    //   }
    // },

    ...initialState?.settings,
  };
};
